<template>
  <div class="p-process flex-col h-full bg-#f7f9fc">
    <div class="auto-bg">
      <div
        class="flex justify-between"
        style="
          box-shadow:
            rgba(0, 0, 0, 0.1) 0 0 4px,
            rgba(9, 30, 66, 0.08) 0 1px 10px;
        "
      >
        <div class="flex-1 flex pb-12 pt-12 px-20">
          <div class="flex-1 flex">
            <h4 class="mb-0 lh-32px">{{ styleName }}</h4>
          </div>
          <div class="flex-shrink-0">
            <a-space>
              <a-button type="primary" @click="onSave">提交保存</a-button>
            </a-space>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-1 mt-8 p-15 bg-white cus-scroll-y">
      <a-spin :spinning="loading">
        <VueDraggable
          v-model="process"
          target=".sort-target"
          handle=".cursor-move"
          :animation="150"
        >
          <table class="p-process-table">
            <thead>
              <tr>
                <th style="width: 100px">序号</th>
                <th style="width: 300px">工序名称</th>
                <th v-for="size in sizes">{{ size.name }}</th>
                <th class="w-100">操作</th>
              </tr>
            </thead>
            <tbody class="sort-target">
              <tr v-for="(item, index) in process">
                <td>
                  <div class="flex">
                    <UnorderedListOutlined class="cursor-move"></UnorderedListOutlined>

                    <span class="flex-1 text-center">{{ index + 1 }}</span>
                  </div>
                </td>
                <td>
                  <a-auto-complete
                    :class="{ 'ant-input-status-error': isError(item.name) }"
                    size="small"
                    @focus="() => onSearch(item.name)"
                    :options="options"
                    class="w-full"
                    placeholder="请输入工序名称"
                    @search="onSearch"
                    @select="(v, row) => onTplSelect(row, item)"
                    v-model:value="item.name"
                  ></a-auto-complete>
                </td>
                <td v-for="p in item.prices">
                  <a-input-number
                    :class="{ 'ant-input-number-status-error': isError(p.price) }"
                    v-model:value="p.price"
                    class="w-full"
                    placeholder="请输入价格"
                    size="small"
                    :min="0"
                  >
                    <template #addonAfter>元</template>
                  </a-input-number>
                </td>
                <td>
                  <a-button
                    v-if="process.length > 1"
                    @click="onRemoveProcess(index)"
                    type="primary"
                    size="small"
                    danger
                  >
                    删除
                  </a-button>
                </td>
              </tr>
            </tbody>
          </table>
        </VueDraggable>
      </a-spin>
      <div class="pt-15 pb-10">
        <a-button class="w-1100px" type="dashed" @click="addRow">
          新增工序
          <template #icon>
            <PlusOutlined></PlusOutlined>
          </template>
        </a-button>
      </div>
    </div>
    <!--    <div class="w-320px bg-white p-15" border-l="1px solid light_border">-->
    <!--      <tpl-list></tpl-list>-->
    <!--    </div>-->
  </div>
</template>
<script setup lang="ts">
import tplList from './tpl-list.vue'
import { PlusOutlined, UnorderedListOutlined } from '@ant-design/icons-vue'
import styleApi, { createStyleProcess } from '@/api/style.ts'
import templateApi, { PriceDto } from '@/api/processTemplate.ts'
import { useRoute } from 'vue-router'
import { SizeDto } from '@/api/size.ts'
import { ProcessDto } from '@/api/process.ts'
import { isNull, isUndefined } from 'xe-utils'
import { message as Message, Modal } from 'ant-design-vue'
import useLoading from '@/hooks/loading.ts'
import { VueDraggable } from 'vue-draggable-plus'

const route = useRoute()
const { setLoading, loading } = useLoading()

const isSubmit = ref(false)
const options = ref<{ value: string; prices: PriceDto[] }[]>([])

const sizes = ref<SizeDto>([])
const styleName = ref('')

const process = ref<ProcessDto[]>([])

function isError(v: any) {
  return isSubmit.value && (isNull(v) || isUndefined(v))
}

function validate() {
  let valid = true
  process.value.forEach((p) => {
    if (isError(p.name)) {
      valid = false
    }
    p.prices.forEach((price) => {
      if (isError(price.price)) {
        valid = false
      }
    })
  })

  return valid
}

async function render() {
  styleApi.get(route.params.id).then(({ data }) => {
    styleName.value = data.group.name + data.model.code + ` (${data.model.name})`
    sizes.value = data.sizes.map((s) => s.size)
    process.value = data.process

    if (process.value.length == 0) {
      addRow()
    }
  })
}

function addRow() {
  process.value.push({
    index: process.value.length + 1,
    name: null,
    prices: sizes.value.map((s) => {
      return {
        sizeId: s.id,
        price: null,
      }
    }),
  })
}

function onRemoveProcess(index: number) {
  process.value = process.value.filter((p, i) => i != index)
}

function onSave() {
  isSubmit.value = true
  if (validate()) {
    Modal.confirm({
      title: '提示',
      type: 'info',
      content: '确定提交保存当前工序配置？',
      onOk: () => {
        setLoading(true)
        process.value.forEach((p, i) => {
          p.index = i + 1
        })
        createStyleProcess(route.params.id, process.value).then(() => {
          render()
          Message.success('提交成功！')
          setLoading(false)
        })
      },
    })
  } else {
    Message.error('请填写完整！')
  }
}

function onSearch(value: string) {
  if (!value) {
    return (options.value = [])
  }
  templateApi
    .page({
      page: 1,
      size: 10,
      sort: 'createdAt',
      model: {
        name: value,
      },
    })
    .then(({ data }) => {
      options.value = data.record.map((item) => {
        return {
          value: item.name,
          prices: item.prices,
        }
      })
    })
}

function onTplSelect(
  row: { row: { value: string; prices: PriceDto[] }; prices: PriceDto[] },
  form: any,
) {
  form.name = row.value
  ;(form.prices || []).forEach((price) => {
    const target = row.prices.find((p) => p.sizeId == price.sizeId)
    if (target) {
      price.price = target.price
    }
  })
}

onMounted(() => {
  render()
})
</script>
<style lang="less" scoped>
.p-process {
  &-table {
    width: 1100px;
    border-collapse: collapse;
    th {
      background-color: #f6f6f7;
    }
    td,
    th {
      border: 1px solid #f0f0f0;
      font-size: 14px;
      padding: 8px 16px;
      text-align: center;
    }
  }
}
</style>
